<template>
  <div>
    <h2>扫码登录</h2>
    <div v-if="qrCodeUrl">
      <qrcode-vue :value="qrCodeUrl" :size="200" />
    </div>
    <p>{{ status }}</p>
    <p></p>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import QrcodeVue from "qrcode.vue";
import { getQrGenerate, getQrStatus } from "@/api/modules/qrLogin"; // 你自己封装的请求模块
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { getUserInfoApi, loginApis } from "@/api/modules/login";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { useUserStore } from "@/stores/modules/admin";
import { useInfoStore } from "@/stores/modules/info";
import { ElMessage, ElNotification } from "element-plus";
import { getTimeState } from "@/utils";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const router = useRouter();
const loading = ref(false);
const loginForm = reactive({
  account: "s",
  password: "1"
});
interface GenerateQrRes {
  loginKey: string;
  status: string;
}

interface StatusRes {
  status: string;
}

const qrCodeUrl = ref<string>("");
const loginKey = ref<string>("");
const status = ref<string>("等待扫码...");

onMounted(async () => {
  try {
    // 生成二维码
    const res: GenerateQrRes = await getQrGenerate();
    loginKey.value = res.loginKey;
    console.log("loginKey:", loginKey.value);

    // 二维码内容（手机扫码后访问的确认页面地址）
    // qrCodeUrl.value = `http://192.168.1.103:8848/scanConfirm?loginKey=${loginKey.value}`;
    qrCodeUrl.value = `http://192.168.1.103:8848/scanConfirm?loginKey=${loginKey.value}`;
    console.log("二维码 URL:", qrCodeUrl.value);
    // 轮询状态
    const timer = setInterval(async () => {
      const s: StatusRes = await getQrStatus(loginKey.value);
      status.value = s.status;
      if (s.status.startsWith("CONFIRMED")) {
        clearInterval(timer);
        // alert("登录成功，用户ID: " + s.status.split(":")[1]);
        loading.value = true;
        // 1.执行登录接口
        const response = await loginApis(loginForm);
        const { data } = response;
        // 设置用户信息到store
        userStore.setToken(data.token);
        userStore.setUserId(data.id);
        userStore.setIsSuper(data.isSuper);
        const res = await getUserInfoApi();
        useInfoStore().setInfo({
          avatar: res.data.avatar,
          email: res.data.email,
          gender: res.data.gender,
          nickName: res.data.nickname
        });
        // 2.添加动态路由
        await initDynamicRouter();
        // 3.清空 tabs、keepAlive 数据
        tabsStore.setTabs([]);
        keepAliveStore.setKeepAliveName([]);
        // 4.跳转到首页
        router.push(HOME_URL);
        ElNotification({
          title: getTimeState(),
          message: "欢迎登录 衣合客栈后台管理系统",
          type: "success",
          duration: 3000
        });
        loading.value = false;
      }
    }, 2000);
  } catch (err) {
    console.error("生成二维码失败", err);
  }
});
</script>
